const utility = require('utility');
class Merchants {
    /**
     * 获取商家信息
     * @api {GET}        /                            获取商家信息
     * @apiName           /merchants
     * @apiGroup          Merchants
     * @apiVersion 0.1.0
     * @apiParam          {Int}            page        页数
     * @apiParam          {Int}            limit       条数
     * @apiParam          {String}         keywords    关键字
     * @apiSuccessExample Success-Response:
     * {
        "code": 0,
        "msg": "success",
        "data": {
        "count": 1,
        "rows": [
            {
                "id": 7,
                "username": "editor",
                "avatar": "http://47.92.129.24/static/upload/20190604/90a4cead0df99.jpeg",
                "role_id": 2,
                "contract": 0.5,
                "status": true,
                "phone": 15632325645
            }
        ]
        }
     }
     */
    async index(ctx) {
        const {
            db,
            Op,
            request: {
                query: { page = 1, limit = 10, keywords = '' }
            },
            user: {
                User: {
                    role: { role }
                }
            }
        } = ctx;

        let condition = {
            limit: parseInt(limit),
            offset: (parseInt(page) - 1) * 10,
            where: {
                isAdmin: 0,
                status: 1
            },
            attributes: [
                'id',
                'username',
                'avatar',
                'role_id',
                'contract',
                'status',
                'phone',
                'money',
                'createdAt'
            ]
        };
        //如果关键字不为空
        if (keywords.trim()) {
            condition.where = {
                isAdmin: 0,
                [Op.or]: [
                    { username: { [Op.like]: '%' + keywords.trim() + '%' } },
                    { phone: { [Op.like]: '%' + keywords.trim() + '%' } }
                ]
            };
        }

        if (role !== 'admin') {
            condition.where.id = ctx.user.User.id;
        }
        //查询所有
        let data = await db.Admin.findAndCountAll(condition);
        ctx.success(data);
    }
    /**
     * 获取商家收入明细
     * @api {GET}         /detail                            获取商家收入明细
     * @apiName           /merchants/detail
     * @apiGroup          Merchants
     * @apiVersion 0.1.0
     * @apiParam          {Int}            id         页数
     * @apiSuccessExample Success-Response:
     * {
        "code": 0,
        "msg": "success",
        "data": {
            {
                "id": 2,
                "userId": 3,
                "merchantId": 7,
                "deviceId": 1,
                "address": "四川省成都市双流区麓山大道一段8号",
                "amount": "30.00",
                "payment": "会员抵扣",
                "status": true,
                "createdAt": "2019-06-04T07:48:38.000Z",
                "updatedAt": "2019-06-04T07:48:41.000Z",
                "userData": {
                    "id": 3,
                    "nickName": "四面是海",
                    "phone": "17726376713"
                }
            }
        }
      }
     */
    async detail(ctx) {
        const {
            db,
            Op,
            request: {
                query: { page = 1, aId, startTime, endTime }
            }
        } = ctx;

        if (!startTime || !endTime) {
            ctx.errors('参数错误');
            return;
        }

        let condition = {
            limit: 10,
            offset: (parseInt(page) - 1) * 10,
            where: {
                merchantId: aId,
                createdAt: {
                    [Op.between]: [startTime, endTime]
                },
                type: 3
            },
            include: {
                as: 'userData',
                attributes: ['id', 'nickName', 'phone'],
                required: true,
                model: db.User
            }
        };

        let data = await db.Use.findAndCountAll(condition);
        ctx.success({ row: data });
    }
    /**
     * 新增商户
     * @api {POST}        /                             新增商户
     * @apiName           /merchants
     * @apiGroup          Merchants
     * @apiVersion 0.1.0
     * @apiParam          {String}         username     商户名称
     * @apiParam          {Number}         phone        手机号
     * @apiParam          {String}         avatar       头像
     * @apiParam          {Number}         contract     合同分成比例
     * @apiSuccessExample Success-Response:
     * {
        "code": 0,
        "msg": "success",
        "data": {}
      }
     */
    async create(ctx) {
        const {
            db,
            request: {
                body: { username, phone }
            },
            user: {
                User: {
                    role: { role }
                }
            }
        } = ctx;

        if (!username || !phone) {
            ctx.errors('参数错误，请认真检查');
            return;
        }

        let merchants = await db.Admin.findOne({ where: { phone: phone } });
        if (merchants) {
            ctx.errors('已存在该商户');
            return;
        }

        let condition = {
            where: {
                username: username,
                phone: phone
            },
            defaults: {
                username: username,
                phone: phone,
                contract: 0,
                avatar:
                    'https://wx.qlogo.cn/mmopen/vi_32/J0xZFvRhWpe2ia0AAjGGdNId3QA7jibkyjEjSIUG5OYJBrGwauw9CwUny59679YHg2OBctoh7UcEt1z7oibL1MTEA/132',
                password: utility.md5('' + phone + ''),
                role_id: 2,
                status: 1
            }
        };
        if (role !== 'admin') {
            ctx.errors('您暂无权限');
            return;
        }
        db.Admin.findOrCreate(condition);
        ctx.success();
    }
    /**
     * 软删除商户
     * @api {DELETE}      /:id                            软删除商户
     * @apiName           /merchants
     * @apiGroup          Merchants
     * @apiVersion 0.1.0
     * @apiSuccessExample Success-Response:
     * {
        "code": 0,
        "msg": "success",
        "data": {}
      }
     */
    async deletes(ctx) {
        const {
            db,
            params: { id },
            user: {
                User: {
                    role: { role }
                }
            }
        } = ctx;

        let condition = {
            where: {
                id: id
            }
        };
        if (role !== 'admin') {
            ctx.errors('您暂无权限');
            return;
        }
        let data = await db.Admin.findOne(condition);
        data.status = 0;
        data.save();
        ctx.success();
    }
    /**
     * 查询商户，多选框使用
     * @api {POST}        /select                             查询商户，多选框使用
     * @apiName           /merchants/select
     * @apiGroup          Merchants
     * @apiVersion 0.1.0
     * @apiSuccessExample Success-Response:
     * {
        "code": 0,
        "msg": "success",
        "data": {}
      }
     */
    async select(ctx) {
        const {
            db,
            user: {
                User: {
                    role: { role }
                }
            }
        } = ctx;
        let data = await db.Admin.findAll({
            where: { isAdmin: 0, status: 1 },
            attributes: ['id', 'username']
        });
        if (role !== 'admin') {
            ctx.errors('您暂无权限');
            return;
        }
        ctx.success(data);
    }
    /**
     * 编辑商户
     * @api {PUT}        /:id                             编辑商户
     * @apiName           /merchants
     * @apiGroup          Merchants
     * @apiVersion 0.1.0
     * @apiParam          {String}         username     商户名称
     * @apiParam          {Number}         phone        手机号
     * @apiSuccessExample Success-Response:
     * {
        "code": 0,
        "msg": "success",
        "data": {}
      }
     */
    async editor(ctx) {
        const {
            db,
            params: { id },
            request: {
                body: { username, phone }
            },
            user: {
                User: {
                    role: { role }
                }
            }
        } = ctx;

        if (!username || !phone) {
            ctx.errors('参数错误，请认真检查');
            return;
        }

        if (role !== 'admin') {
            ctx.errors('您暂无权限');
            return;
        }

        let data = await db.Admin.findOne({ where: { id: id } });

        data.username = username;

        data.phone = phone;

        data.password = utility.md5('' + phone + '');

        data.save();

        ctx.success('', '编辑成功');
    }
}
module.exports = new Merchants();
